package com.algo.url;

import java.io.FileWriter;
import java.io.IOException;
import java.util.HashMap;
import java.util.Map;

public class ScratchLogger {
	
	private FileWriter fw;
	private Map<String, Integer> exceptionTimes;
	private int failedUrlNum;
	private int suceededUrlNum;
	private int[] titleKeywordsDescNum = new int[3];
	
	public ScratchLogger(String fileName){
		try{
			fw = new FileWriter(fileName);
			exceptionTimes = new HashMap<String, Integer>();
		}catch(IOException ex){
			new RuntimeException(ex);
		}
	}
	
	public synchronized void logExeption(String url, Exception e){
		try{
			String exceptionName = e.getClass().getName();
			fw.write(url + "^" + exceptionName + "\n");
			Integer times = exceptionTimes.get(exceptionName);
            exceptionTimes.put(exceptionName, times==null?1:times+1);
			//exceptionTimes.put(exceptionName, 1 + exceptionTimes.getOrDefault(exceptionName, 0));
			failedUrlNum++;
		}catch(IOException ex){
			new RuntimeException(ex);
		}
	}
	public synchronized void afterScratchUrl(String titleKeywordsDesc){
		
		String[] items = titleKeywordsDesc.split("\\t");
		if(items.length <= 3){
			suceededUrlNum++;
			for(int i = 0; i < items.length; i++)
				if(items[i].length() > 0)	titleKeywordsDescNum[i]++;
		}
		else
			throw new RuntimeException("ERROR: titleKeywordsDesc:" + titleKeywordsDesc + " has " + items.length + " \\t delimiter");
		
	}
    public synchronized void afterScratchUrl(int[] isEmpty){
        suceededUrlNum++;
        for(int i = 0; i < isEmpty.length; i++)
          titleKeywordsDescNum[i] = titleKeywordsDescNum[i] + isEmpty[i];

    }
	public void closeLogger(){
		try{
			fw.close();
		}catch(IOException ex){
			new RuntimeException(ex);
		}
	}
	
	public void printScratchInfo(){
		System.out.format("INFO: Suceeded to scratch %d urls:\n", suceededUrlNum);
		System.out.format("\tsuceeded scrathing %8d title\n", titleKeywordsDescNum[0]);
		System.out.format("\tsuceeded scrathing %8d keywords\n", titleKeywordsDescNum[1]);
		System.out.format("\tsuceeded scrathing %8d description\n", titleKeywordsDescNum[2]);
		
		System.out.format("INFO: Failed to scratch %d urls:\n", failedUrlNum);
		for(Map.Entry<String, Integer> kv : exceptionTimes.entrySet())
			System.out.format("\t%25s\t%8d\n", kv.getKey(), kv.getValue());
	}

}
